<?php
namespace MobileHome\Controller;

use MobileHome\Model\UserModel;
use Think\Log;

class LoginController extends BaseController
{
    /**
     * @var UserModel|null
     */
    private $_mdlUser = null;

    public function __construct()
    {
        $this->_mdlUser = D('User');
    }

    /**
     * 登录
     */
    public function loginAction()
    {
        $mobile = I('post.mobile');
        $smsCode = I('post.smsCode');
        if ($mobile != $_SESSION['mobile'] || $smsCode != $_SESSION['smsCoce']) {
            $this->json(4001, '登录失败!');
        }

        //注册用户
        $userInfo = $this->_mdlUser->getInfoByMobile($mobile);
        if (!$userInfo) {
//            $data = [
//                'mobile' => $mobile,
//            ];
        }

        //销毁发送验证码的session
        unset($_SESSION['mobile'], $_SESSION['SmsCode']);
//        $data = [
//            'result'   => 1,
//        ];
        $this->json(200, 'SUCCESS');
    }

    /**
     * 发送验证码
     */
    public function sendSmsCodeAction()
    {
        $mobile = I('post.mobile');
        if (!preg_match('/^1[3|4|5|7|8][0-9]{9}$/', $mobile)) {
            $this->json(4001, '请输入正确的手机号码');
        }
                $code = '888888';

//        //短信
//        vendor('Sms.YunpianSms', '', '.class.php');
//        $apikey = C('YUNPIAN.apikey');
//        /** @var \YunpianSms $objSms */
//        $objSms = \YunpianSms::getInstance($apikey);
//        $code = mt_rand(100000, 999999);
//        $text = sprintf("【聚合信用】验证码：%s，10分钟内输入有效。", $code);
//        $res = $objSms->singleSend($mobile, $text);
//        if (false === $res) {
//            $error = $objSms->getError();
//            $message = '聚合信用-发送短信失败 Mobile:' . $mobile . ' ErrorInfo:' . json_encode($error, JSON_UNESCAPED_UNICODE);
//            Log::write($message);
//            $this->json(4002, '发送验证码失败,请重试!');
//        }

        $_SESSION['smsCoce'] = $code;
        $_SESSION['mobile'] = $mobile;
//        $data = [
//            'result' => 1,
//        ];
        $this->json('200', 'SUCCESS');
    }
}